<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="角色描述"
        :label-width="formLabelWidth"
        prop="description"
      >
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitHandle">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { addRole, updateRole } from '@/api/setting'
export default {
  name: '',
  props: {
    isEdit: {
      type: Boolean
    },
    dialogFormVisible: {
      type: Boolean
    },
    row: {
      type: Object,
      default: () => {}
      // 假如row为数组,default: () =>[]
    }
  },
  data() {
    return {
      /* 对话框 */
      form: {
        name: '',
        description: ''
      },
      formLabelWidth: '120px',
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},

  watch: {
    isEdit: {
      handler(newVal) {
        if (newVal) {
          // this.form = this.row
          this.form = JSON.parse(JSON.stringify(this.row))
        }
      },
      immediate: true // 立即触发
    }
  },

  created() {},

  methods: {
    cancel() {
      this.$emit('update:dialogFormVisible', false)
    },
    submitHandle() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 添加
    async doAdd() {
      const res = await addRole(this.form)
      this.success()
    },

    async doEdit() {
      // 编辑
      await updateRole(this.form)
      this.success()
    },
    success() {
      // 成功后需要做的操作
      // 关闭对话框+刷新页面
      this.$emit('success')
    }
  }
}
</script>
<style lang="less" scoped></style>
